const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const Post = require('../models/Post');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = 'public/uploads/posts';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 限制5MB
    files: 9 // 最多9张图片
  },
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只能上传图片文件'));
    }
  }
});

// 获取帖子列表
router.get('/posts', async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      type, 
      userId,
      tag,
      near 
    } = req.query;

    const query = {};
    
    // 添加筛选条件
    if (type) query.type = type;
    if (userId) query.userId = userId;
    if (tag) query.tags = tag;
    
    // 处理地理位置查询
    if (near) {
      const [lng, lat] = near.split(',').map(Number);
      query.location = {
        $near: {
          $geometry: {
            type: 'Point',
            coordinates: [lng, lat]
          },
          $maxDistance: 5000 // 5公里内
        }
      };
    }

    const posts = await Post.find(query)
      .sort({ createdAt: -1 })
      .skip((page - 1) * limit)
      .limit(limit)
      .populate('userId', 'username avatar')
      .lean();

    const total = await Post.countDocuments(query);

    res.json({
      posts,
      total,
      totalPages: Math.ceil(total / limit),
      currentPage: parseInt(page)
    });
  } catch (error) {
    console.error('获取动态列表失败:', error);
    res.status(500).json({ message: '获取动态列表失败' });
  }
});

// 发布动态
router.post('/posts', auth, upload.array('images', 9), async (req, res) => {
  try {
    const { content, tags, type, relatedResourceId, location, address } = req.body;

    // 验证必填字段
    if (!content || content.trim().length === 0) {
      return res.status(400).json({ message: '内容不能为空' });
    }

    // 处理上传的图片
    const images = req.files ? req.files.map(file => `/uploads/posts/${file.filename}`) : [];

    // 创建新动态
    const post = new Post({
      userId: req.userId,
      username: req.user.username,
      content: content.trim(),
      images,
      tags: tags ? JSON.parse(tags) : [],
      type: type || 'general',
      relatedResourceId,
      location: location ? {
        type: 'Point',
        coordinates: JSON.parse(location)
      } : undefined,
      address
    });

    await post.save();

    // 返回完整的帖子信息
    const populatedPost = await Post.findById(post._id)
      .populate('userId', 'username avatar')
      .lean();

    res.status(201).json(populatedPost);
  } catch (error) {
    console.error('发布动态失败:', error);
    res.status(500).json({ 
      message: '发布失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
});

// 点赞帖子
router.post('/posts/:id/like', auth, async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
    if (!post) {
      return res.status(404).json({ message: '帖子不存在' });
    }

    const hasLiked = post.likes.includes(req.userId);
    if (hasLiked) {
      post.likes = post.likes.filter(id => !id.equals(req.userId));
    } else {
      post.likes.push(req.userId);
    }

    await post.save();
    res.json({ likes: post.likes.length, liked: !hasLiked });
  } catch (error) {
    console.error('点赞失败:', error);
    res.status(500).json({ message: '点赞失败' });
  }
});

// 评论帖子
router.post('/posts/:id/comments', auth, async (req, res) => {
  try {
    const { content } = req.body;
    const post = await Post.findById(req.params.id);
    
    if (!post) {
      return res.status(404).json({ message: '帖子不存在' });
    }

    const comment = {
      userId: req.userId,
      username: req.user.username,
      content
    };

    post.comments.push(comment);
    await post.save();

    res.status(201).json(comment);
  } catch (error) {
    console.error('评论失败:', error);
    res.status(500).json({ message: '评论失败' });
  }
});

module.exports = router; 